<?php

namespace app\admin\controller;

use app\admin\model\auser;
use think\Db;
use think\Request;
use think\Validate;

class User extends AdminBase
{
    /**
     *展示
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        if (Request::instance()->isPost()) {
            try {
                $page = input('page/d', 1);
                $limit = input('limit/d', 10);
                $where = [];

                $rid = input('rid/d');
                if (!empty($rid)) $where['a.rid'] = $rid;

                $status = input('a.status/d', -1);
                if ($status >= 0) $where['a.status'] = $status;

                $adname = input('adname/s');
                if (!empty($adname)) $where['a.adname'] = ['like', '%' . $adname . '%'];

                //排序
                $order = input('order/s', 'desc');
                $field = input('field/s', 'update_time');

                $list = Db::name('auser')->alias('a');
                $count = Db::name('auser')->alias('a');

                if (!empty($where)) {
                    $count = $count->where($where);
                    $list = $list->where($where);
                }

                $list = $list->join('arole r', 'r.roleid=a.rid', 'left')
                    ->field('a.adid,a.adname,a.rid,a.status,FROM_UNIXTIME(a.create_time,"%Y-%m-%d %H:%i:%s") as create_time,FROM_UNIXTIME(a.update_time,"%Y-%m-%d %H:%i:%s") as update_time,r.rolename')
                    ->limit(($page - 1) * $limit, $limit)
                    ->order($field, $order)
                    ->select();

                $count = $count->count();

                $json = ['code' => 0, 'msg' => 'success', 'data' => $list, 'count' => $count];
            } catch (\Exception $e) {
                $json = ['code' => -1, 'msg' => $e->getMessage()];
            }
            return json($json);
        }

        //查询角色
        $role = Db::name("arole")->select();
        $this->assign('role', $role);

        return $this->fetch();
    }

    /**
     * 添加/编辑
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function save()
    {
        if (Request::instance()->isPost()) {
            try {
                $post = input();
                $type = input('type/d', 1);

                $rule = [
                    ['adid', 'egt:0', 'adid不合法'],
                    ['status', 'require|in:0,1', '用户密码不能超过16个字符'],
                ];
                if ($type == 1) $rule = array_merge(
                    $rule,
                    [
                        ['rid', 'require|egt:0', '缺失所属角色|所属角色不合法'],
                        ['adname', 'require|length:1,20', '请填写用户名|用户名不能超过20个字符'],
                        ['password', 'length:0,16', '用户密码不能超过16个字符']
                    ]
                );

                $validate = new Validate($rule);
                if (!$validate->check($post)) throw new \Exception($validate->getError());

                //密码处理
                $post['salt'] = auser::salt();
                $post['password'] = auser::encrypt($post['password'], $post['salt']);

                empty($post['adid']) ? auser::auserAdd($post) : auser::auserUpdate($post);

                $json = ['status' => 200, 'msg' => 'success'];
            } catch (\Exception $e) {
                $json = ['status' => 400, 'msg' => $e->getMessage()];
            }
            return json($json);
        }

        $id = input('adid/d');
        $this->assign('id', $id);

        if (!empty($id)) {
            $info = Db::name('auser')->find($id);
            $this->assign('info', $info);
        }

        //查询角色
        $role = Db::name("arole")->select();
        $this->assign('role', $role);

        $type = input('type', 'add');
        $this->assign('type', $type);

        return $this->fetch();
    }

    /**
     * 删除节点
     * @return \think\response\Json
     */
    public function del()
    {
        try {
            $adid = input('adid/d');
            if (empty($adid)) throw new \Exception('缺少id');

            auser::auserDel(['adid' => $adid]);

            $json = ['status' => 200, 'msg' => 'success'];
        } catch (\Exception $e) {
            $json = ['status' => 400, 'msg' => $e->getMessage()];
        }
        return json($json);
    }
}